import axiosInstance from '@/tools/request'
import type { GeneratorTable } from '@/api/generator/generator'
import axios from 'axios'


//添加表
export const tableAdd = (table: GeneratorTable) => {
  return axiosInstance({
    url: '/generator/table',
    method: 'post',
    data: table
  })
}

//删除表
export const tableRemove = (tableId: number) => {
  return axiosInstance({
    url: `/generator/table/${tableId}`,
    method: 'delete'
  })
}
//修改表
export const tableModify = (table: GeneratorTable) => {
  return axiosInstance({
    url: `/generator/table`,
    method: 'put',
    data: table
  })
}

//获取表列表
export const tableList = (query: GeneratorTable, params: any) => {
  return axiosInstance({
    url: '/generator/table/list',
    params: params,
    data: query,
    method: 'post'
  })
}
//通过ID获取表
export const tableById = (id: number) => {
  return axiosInstance({
    url: `/generator/table/${id}`,
    method: 'get'
  })
}
//代码预览
export const tableView = (params: any) => {
  return axiosInstance({
    url: `/generator/table/preview`,
    method: 'get',
    params: params
  })
}

//下载文件
export const downloadCode = (params: any) => {
  const data = axios.get('/api/generator/table/download', {
    params: params,
    responseType: 'blob',
    headers: { token: localStorage.getItem('token') }
  })

  data.then((result) => {
    const data = result.data as Blob
    //@ts-ignore
    const disposition = result.headers.get('content-disposition') as string
    const index = disposition.indexOf('=')
    const filename = disposition.substring(index + 1)

    const src = window.URL.createObjectURL(data)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.setAttribute('download', filename)
    link.href = src
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(src)
  })
}

